package com.wqiuqiu.gulimall.auth.web;


import com.wqiuqiu.common.R;
import com.wqiuqiu.common.constant.RedisConstant;
import com.wqiuqiu.common.excption.BizCodeEnume;
import com.wqiuqiu.common.to.thridservice.MailTo;
import com.wqiuqiu.gulimall.auth.feign.MemberFeignService;
import com.wqiuqiu.gulimall.auth.feign.ThirdFeignService;
import com.wqiuqiu.gulimall.auth.vo.RegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Validated
@Controller
public class RegisterController {

    @Autowired
    StringRedisTemplate stringRedisTemplte;
    @Autowired
    ThirdFeignService thirdFeignService;
    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendMail")
    public R register(@RequestParam("eamil") @NotBlank(message = "邮箱格式错误") String eamil) {
        //验证码校验以及防刷 redis
        String redisCode = stringRedisTemplte.opsForValue().get(RedisConstant.eamilPre + eamil);
        if (StringUtils.isNotEmpty(redisCode)) {
            //说明该邮箱之前发送过验证码
            if (System.currentTimeMillis() - Long.parseLong(redisCode.split("_")[1]) < 60000) {
                //距离上一次方式验证码处于60s之内
                return R.error(BizCodeEnume.EMAIL_EXCEPTION.getCode(), BizCodeEnume.EMAIL_EXCEPTION.getMessage());
            }
        }
        MailTo mailTo = new MailTo();
        mailTo.setTo(eamil);
        mailTo.setSubject("验证码");
        String code = UUID.randomUUID().toString().substring(0, 4);
        mailTo.setBody(code);
        try {
            R r = thirdFeignService.sendMail(mailTo);
        } catch (Exception e) {
            if (e instanceof feign.RetryableException) {
                System.out.println("报错信息：" + e.getMessage());
                Class<? extends Exception> aClass = e.getClass();
                System.out.println("异常类型" + aClass.getName());
            } else {
                return R.error(BizCodeEnume.Feign_EXCEPTION.getCode(), BizCodeEnume.Feign_EXCEPTION.getMessage());
            }
        }

        stringRedisTemplte.opsForValue().set(RedisConstant.eamilPre + eamil, code + "_" + System.currentTimeMillis(), 60, TimeUnit.MINUTES);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid RegisterVo vo, RedirectAttributes model) {
        //TODO 异常做全局处理 发生错误 需要返回异常信息给前端，而不是简单的跳转或者刷新，转发
        //"redirect:http://auth.gulimall.com/reg.html";
        //对验证码进行校验
        String eamil = vo.getEamil();
        String redisCode = stringRedisTemplte.opsForValue().get(RedisConstant.eamilPre + eamil);
        HashMap<String, String> map = new HashMap<>();
        if (StringUtils.isNotEmpty(redisCode)) {
            if (redisCode.split("_")[0].equalsIgnoreCase(vo.getCode())) {
                stringRedisTemplte.delete(RedisConstant.eamilPre + eamil);
                //进行注册服务
                R r = null;
                try {
                    r = memberFeignService.memberReg(vo);
                } catch (Exception e) {
                    if (r == null) {
                        map.put("msg", BizCodeEnume.Feign_EXCEPTION.getMessage());
                        model.addFlashAttribute("errors", map);
                        return "redirect:http://auth.gulimall.com/reg.html";
                    }
                }
                //TODO 只要发送超时返回值就是null???
                if (r.getCode() != 0) {
                    map.put("msg", r.get("msg").toString());
                    model.addFlashAttribute("errors", map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                //前端传回的验证码不正确
                map.put("msg", BizCodeEnume.CODE_NOFALSE_EXCEPTION.getMessage());
                model.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //验证码过期
            map.put("msg", BizCodeEnume.CODE_OUT_TIME_EXCEPTION.getMessage());
            model.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
}
